package com.ch.light.web.service.impl;

import com.ch.light.mybatis.ParamFilter;
import com.ch.light.mybatis.pojo.DataSourceCfg;
import com.ch.light.mybatis.tools.SQLRunner;
import com.ch.light.web.mapper.SqlScriptMapper;
import com.ch.light.web.model.DataSourceConfig;
import com.ch.light.web.model.SqlScript;
import com.ch.light.web.service.DataSourceConfigService;
import com.ch.light.web.service.SqlScriptService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;

/**
 * 描述：com.ch.light.web.service.impl
 *
 * @author 80002023
 *         2017/5/13.
 * @version 1.0
 * @since 1.8
 */
@Service
public class SqlScriptServiceImpl implements SqlScriptService {

    @Autowired
    private SqlScriptMapper sqlScriptMapper;

    @Autowired
    private DataSourceConfigService dataSourceConfigService;

    @Override
    public int add(SqlScript record) {
        return 0;
    }

    @Override
    public int update(SqlScript record) {
        return 0;
    }

    @Override
    public List<SqlScript> getList(ParamFilter paramFilter) {
        int pageNum = paramFilter.getPage().getPageNo();
        int pageSize = paramFilter.getPage().getPageSize();
        PageHelper.startPage(pageNum, pageSize, true, false, false);
        Example example = new Example(SqlScript.class);
        Map<String, Object> param = paramFilter.getParam();
        return sqlScriptMapper.selectByExample(example);
    }

    @Override
    public SqlScript findById(Long id) {
        return sqlScriptMapper.selectByPrimaryKey(id);
    }

    @Override
    public int exe(String dsCode, String sql) {
        DataSourceConfig dsConfig = dataSourceConfigService.findByCode(dsCode);
        if (dsConfig != null) {
            DataSourceCfg cfg = new DataSourceCfg();
            BeanUtils.copyProperties(dsConfig, cfg);
            int status = SQLRunner.executeDDL(cfg, sql);
            if (status > 0) {
                return  status;
            }
        }
        return 0;
    }
}
